# -*- coding: utf-8 -*-
'''
@author: atuo.cn
'''
import os
import sys
import re
from configparser import ConfigParser
from tkinter import StringVar,IntVar, BooleanVar

class Settings:
    
    def __init__(self):
        self.configfile=self._getconfigfile()
        
        self.default_values={
            "IncludeIntro": True,
            "lang":"zh-CN",
            "encoding":"gb18030",
            "kindlegen":self._get_default_kindlegen(),
            "kindlearg":"-c1"            
        }

        self.vars={
            k: self._create_var(v)
            for k,v in self.default_values.items()
        }        
        
        self.loadconfig()
    
    @staticmethod
    def _create_var(v):
        if isinstance(v, int):
            return IntVar(value=v)
        elif isinstance(v, bool):
            return BooleanVar(value=v)
        else:
            return StringVar(value=v)
            
    def _getconfigfile(self):
        home=os.path.expanduser("~")
        configpath=""
        if os.name=="nt":
            configpath=os.getenv("APPDATA",os.path.join(home,"AppData","Roaming"))
        elif os.name=="posix":
            configpath=os.getenv("XDG_CONFIG_HOME", os.path.join(home,".config"))
        elif os.name=="mac":
            configpath=os.path.join(home,"Library","Application Support")
            
        if configpath:
            configpath=os.path.join(configpath,"text2ebook")
        else:
            configpath=os.path.join(home,".text2ebook")
        return os.path.join(configpath, "settings.config")

    def _get_default_kindlegen(self):
        name_mapping={
            "linux.*":"linux",
            "win32":"win32",
            "cygwin":"win32",
            "darwin":"mac",
            "__default__":"linux"
        }
        platform=sys.platform
        #note: the order of keys is random,
        #so the result is random too if there are two patterns matched.
        it=filter(lambda k:re.match(k, platform), name_mapping.keys())
        platform=name_mapping[next(it, "__default__")]
        ap_path=os.path.normpath(os.path.join(os.path.dirname(__file__),".."))
        kindlegen=os.path.join(ap_path, "kindlegen",platform,"kindlegen")
        return kindlegen
        
    def loadconfig(self):
        #default values of ConfigParser must be string
        default={k:str(v) for k,v in self.default_values.items()}
        parser=ConfigParser(default)
        try:
            parser.read(self.configfile)
            for s in parser.sections():
                for k,v in parser.items(s):
                    if k in self.vars:
                        self.vars[k].set(v)
        except:
            pass

    def saveconfig(self, sections):
        parser=ConfigParser()
        if os.path.exists(self.configfile):
            parser.read(self.configfile)
        for k,v in sections.items():
            parser[k]=v
        
        configpath=os.path.normpath(os.path.dirname(self.configfile))
        if not os.path.isdir(configpath): os.makedirs(configpath)
        
        with open(self.configfile,"w") as f:
            parser.write(f)
        
    def __getitem__(self,key):
        return self.vars[key].get()
    
    def __setitem__(self,key,value):
        self.vars[key].set(value)

    def __contains__(self,item):
        return self.vars.__contains__(item)
        
    def __len__(self):
        return self.vars.__len__()
        
    def __delitem__(self,key):
        del self.vars[key]
        
    def __iter__(self):
        return self.vars.__iter__()
        
    def keys(self):
        return self.vars.keys()
        
    def get(self, key, default=None):
        try:
            return self.vars[key].get()
        except:
            return default
    